<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>课程</span>
        <el-input 
          v-model="searchQuery" 
          placeholder="搜索相关课程..." 
          style="width: 200px; margin-right: 10px;" 
        />
        <div class="extra">
          <el-button @click="clearForm" type="primary">添加课程</el-button>
          <el-button 
            :disabled="selectedCourses.length === 0" 
            @click="deleteSelectedCourses" 
            type="danger">
            批量删除
          </el-button>
        </div>
      </div>
    </template>

    <!-- 添加课程弹窗 -->
    <el-dialog v-model="dialogVisible" :title="name" width="30%">
      <el-form :model="courseModel" :rules="rules" label-width="100px" style="padding-right: 30px">
        <el-form-item label="课程名" prop="name">
          <el-input v-model="courseModel.name" placeholder="请输入课程名称"></el-input>
        </el-form-item>
        <el-form-item label="课程学分" prop="credit">
          <el-input type="number" v-model="courseModel.credit"></el-input>
        </el-form-item>
        <el-form-item label="课程图片" prop="image">
          <el-image :src="courseModel.image" alt="Course Image" class="course-image" />
        </el-form-item>
        <el-form-item label="授课教师" prop="teacherId">
          <el-select v-model="courseModel.teacherId" placeholder="请选择教师">
            <el-option
              v-for="teacher in teachers"
              :key="teacher.id"
              :label="teacher.name"
              :value="teacher.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开课状态" prop="isOpen">
          <el-radio-group v-model="courseModel.isOpen">
            <el-radio :label="1">开课</el-radio>
            <el-radio :label="0">未开课</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="name === '添加课程' ? addCourse() : editCourse()">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 列表 -->
    <el-table :data="paginatedCourses" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection"></el-table-column>
      <el-table-column label="序号" width="100" type="index"> </el-table-column>
      <el-table-column label="课程" prop="name"></el-table-column>
      <el-table-column label="课程图片" width="120">
        <template #default="{ row }">
          <el-image
            :src="row.image"
            class="course-image"
            fit="cover"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="学分" prop="credit"></el-table-column>
      <el-table-column label="授课教师" prop="teacherName"></el-table-column>
      <el-table-column label="开课状态" prop="isOpen">
        <template #default="{ row }">
          <span>{{ row.isOpen === 1 ? '开课' : '未开课' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="选课学生">
        <template #default="{ row }">
          <el-button plain type="success" @click="showStudent(row.id)">查看学生</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="{ row }">
          <el-button :icon="Edit" circle plain type="primary" @click="showCourse(row)"></el-button>
          <el-button :icon="Delete" circle plain type="danger" @click="deleteCourse(row)"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      background
      :current-page="currentPage"
      :page-size="pageSize"
      @current-change="handlePageChange"
      :total="filteredCourses.length">
    </el-pagination>
  </el-card>
</template>

<script setup>
import { Edit, Delete } from '@element-plus/icons-vue';
import { useTokenStore } from '../../stores/token';
import { ref, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import {
  getCourseService,
  addCourseService,
  updateService,
  deleteService,
} from '../../api/course';
import { getTeacherByIdService, getTeacherService } from '../../api/teacher';
import ImageFetcher from '@/utils/imageFetcher';

const router = useRouter();
const teachers = ref([]);
const courses = ref([]);
const selectedCourses = ref([]);
const currentPage = ref(1);
const pageSize = ref(10); // 每页显示的课程数

const getTeachers = async () => {
  let res = await getTeacherService();
  teachers.value = res.data;
};

getTeachers();

const searchQuery = ref('');

const filteredCourses = computed(() => {
  return courses.value.filter(course => {
    return course.name.includes(searchQuery.value);
  });
});

// 计算分页后的课程数据
const paginatedCourses = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  return filteredCourses.value.slice(start, start + pageSize.value);
});

// 弹框标题
const name = ref('');
const dialogVisible = ref(false);

const courseModel = ref({
  name: '',
  credit: '',
  teacherId: '',
  teacherName: '',
  isOpen: '',
  id: 0,
});

// 添加课程表单校验
const rules = {
  name: [{ required: true, message: '请输入课程名称', trigger: 'blur' }],
  credit: [{ required: true, message: '请输入学分', trigger: 'blur' }],
};

// 显示课程列表信息
const courseList = async () => {
  try {
    let res = await getCourseService();
    const coursesData = res.data;

    const token = useTokenStore().token;
    const imageFetcher = new ImageFetcher(token);

    const teacherPromises = coursesData.map(async (course) => {
      try {
        const teacherResponse = await getTeacherByIdService(course.teacherId);
        course.teacherName = teacherResponse.data.name;

        const courseImageUrl = course.image;
        const image = await imageFetcher.fetchImage(courseImageUrl);
        course.image = image; // 将获取到的图片设置回课程对象

        return course;
      } catch (teacherError) {
        console.error(`Error fetching teacher for course ${course.id}:`, teacherError);
        return {
          ...course,
          teacherName: 'Unknown',
          image: null,
        };
      }
    });
    // 等待所有请求完成
    courses.value = await Promise.all(teacherPromises);
  } catch (error) {
    console.error('Error fetching course data:', error);
  }
};

// 处理选择变化的方法
const handleSelectionChange = (selection) => {
  selectedCourses.value = selection;
};

// 批量删除选中的课程
const deleteSelectedCourses = async () => {
  if (selectedCourses.value.length === 0) {
    ElMessage.warning('请选择要删除的课程');
    return;
  }
  ElMessageBox.confirm('您确定要删除这些课程吗?', '注意', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(async () => {
    for (const course of selectedCourses.value) {
      await deleteService(course.id);
    }
    selectedCourses.value = []; // 清空选择
    courseList(); // 刷新课程列表
    ElMessage.success('删除成功');
  })
  .catch(() => {
    ElMessage({
      type: 'info',
      message: '删除已取消',
    });
  });
};

// 页码改变事件
const handlePageChange = (page) => {
  currentPage.value = page;
};

// 添加课程弹窗
const addCourse = async () => {
  let res = await addCourseService(courseModel.value);
  if (res) {
    ElMessage.success(res.message ? res.message : '添加成功');
    courseList();
    dialogVisible.value = false;
  } else {
    ElMessage.error(res.message ? res.message : '很可惜，添加失败了');
  }
};

// 修改是弹窗展示编辑原信息
const showCourse = (row) => {
  dialogVisible.value = true;
  name.value = '修改课程';
  courseModel.value = { ...row };
};

// 编辑课程
const editCourse = async () => {
  let res = await updateService(courseModel.value);
  ElMessage.success(res.message ? res.message : '修改成功!');
  courseList();
  dialogVisible.value = false;
};

// 添加时清空表单数据
const clearForm = () => {
  dialogVisible.value = true;
  name.value = '添加课程';
  courseModel.value.name = '';
  courseModel.value.credit = '';
  courseModel.value.teacherId = '';
  courseModel.value.isOpen = '';
};

// 删除课程
const deleteCourse = async (row) => {
  ElMessageBox.confirm('您确定要删除这个课程吗', '注意', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(async () => {
    let res = await deleteService(row.id);
    courseList();
    dialogVisible.value = false;
    ElMessage({
      type: 'success',
      message: res.message ? res.message : '删除成功',
    });
  })
  .catch(() => {
    ElMessage({
      type: 'info',
      message: '删除已取消',
    });
  });
};

const showStudent = (id) => { 
  router.push({ path: '/course/student', query: { couId: id } }); //携带id查询
};

// 初始化课程列表
courseList();
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
.course-image {
  width: 100%; /* 确保图片占满列宽 */
  height: 100px; /* 设置固定高度 */
}
</style>